package com.xiang.community.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author qixiangLi
 * @Date 2021/10/11
 */
@Component
@Slf4j
public class MailUtil {
    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private TemplateEngine templateEngine;

    public void send(String template, String subject, String to, String url) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom(from);
            helper.setSubject(subject);
            helper.setText(contentFromTemplate(template, to, url), true);
            helper.setTo(to);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            log.error("发送邮件给{}失败。失败信息：{}", to, e.getMessage());
        }
    }

    private String contentFromTemplate(String template, String to, String url) {
        Context context = new Context();
        context.setVariable("to", to);
        context.setVariable("url", url);
        return templateEngine.process(template, context);
    }
}
